package com.ckerchina.admin.ckadmin.service;

import java.util.Date;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ckerchina.admin.ckadmin.consts.ActorType;
import com.ckerchina.admin.ckadmin.dao.AgentOrderDao;
import com.ckerchina.admin.ckadmin.dao.AgentUserDao;
import com.ckerchina.admin.ckadmin.dao.ChargeDetailDao;
import com.ckerchina.admin.ckadmin.dao.CustomerUserDao;
import com.ckerchina.admin.ckadmin.dao.MaterialDao;
import com.ckerchina.admin.ckadmin.dao.MaterialOrderDao;
import com.ckerchina.admin.ckadmin.dao.TeacherInfoDao;
import com.ckerchina.admin.ckadmin.domain.AgentOrder;
import com.ckerchina.admin.ckadmin.domain.AgentUser;
import com.ckerchina.admin.ckadmin.domain.ChargeDetail;
import com.ckerchina.admin.ckadmin.domain.CustomerUser;
import com.ckerchina.admin.ckadmin.domain.Material;
import com.ckerchina.admin.ckadmin.domain.MaterialOrder;
import com.ckerchina.admin.ckadmin.domain.TeacherInfo;
import com.ckerchina.admin.ckadmin.domain.mgr.MgrUser;
import com.ckerchina.admin.ckadmin.exception.ErrorCode;
import com.ckerchina.admin.ckadmin.exception.ZhuziException;
import com.ckerchina.admin.ckadmin.service.mgr.MgrUserDetail;

@Service
@Transactional
public class UpdateService {

	private static final Logger logger = LoggerFactory.getLogger(UpdateService.class);

	@Autowired
	private AgentOrderDao agentOrderDao;

	@Autowired
	private CustomerUserDao customerUserDao;

	@Autowired
	private TeacherInfoDao teacherInfoDao;

	@Autowired
	private ChargeDetailDao chargeDetailDao;

	@Autowired
	private AgentUserDao agentUserDao;
	
	@Autowired
	private MaterialOrderDao materialOrderDao;
	
	@Autowired
	private MaterialDao materialDao;

	@Transactional
	public void addChargeDetail(ChargeDetail charge) {
		MgrUser user = getMgrUser();
		Long operator_id = user.getId();
		String operator_name = user.getName();
		charge.setOperator_id(operator_id);
		charge.setOperator_name(operator_name);
		AgentUser agent = agentUserDao.find(charge.getAgent_id());
		charge.setAgent_name(agent.getAgentName());
		Float left_money = agent.getLeftMoney();
//		Float left_money_new = left_money + charge.getCharge_money();
		charge.setLeft_money(left_money);
		charge.setState(1);
		charge.setCharge_type(1);
		charge.setCreat_time(new Date());
		chargeDetailDao.persist(charge);
//		agent.setLeftMoney(left_money_new);
//		agentUserDao.merge(agent);
	}
	
	@Transactional
	public void deductChargeDetail(ChargeDetail charge) {
		MgrUser user = getMgrUser();
		Long operator_id = user.getId();
		String operator_name = user.getName();
		charge.setOperator_id(operator_id);
		charge.setOperator_name(operator_name);
		AgentUser agent = agentUserDao.find(charge.getAgent_id());
		charge.setAgent_name(agent.getAgentName());
		Float left_money = agent.getLeftMoney();
		Float left_money_new = left_money - charge.getCharge_money();
		charge.setLeft_money(left_money_new);
		charge.setState(2);
		charge.setCharge_type(2);
		charge.setCreat_time(new Date());
		chargeDetailDao.persist(charge);
		agent.setLeftMoney(left_money_new);
		agentUserDao.merge(agent);
	}
	
	@Transactional
	public void updateChargeDetail(ChargeDetail charge) {
		ChargeDetail old = chargeDetailDao.find(charge.getId());
//		
		AgentUser agent = agentUserDao.find(old.getAgent_id());
		Float left_money = agent.getLeftMoney();
		Float left_money_new = left_money + charge.getCharge_money();
		if(charge.getState() == 2)//审核通过
		old.setLeft_money(left_money_new);	
		old.setState(charge.getState());
		chargeDetailDao.merge(old);
		logger.info("更新充值审核信息成功{}", charge);
		
		
		if(charge.getState() == 2)//审核通过
		{			
			agent.setLeftMoney(left_money_new);
		    agentUserDao.merge(agent);
			logger.info("更新充值金额成功{}", charge);
		}
//		
	}

	@Transactional
	public void addAgentOrder(AgentOrder info) {
		MgrUser user = getMgrUser();
		String actortype = user.getActortype();
		logger.info("actortype:{}", actortype);
		String agentid = "0";
		String agent_name = "0";
		
		if (actortype.equals(ActorType.agent.getValue())) {
			agentid = user.getCompanyid();
			agent_name = user.getCompanyname();

		}

		info.setAgent_id(agentid);
		info.setOrder_num(com.ckerchina.admin.ckadmin.utils.GenOrder.getOrderNo());
		info.setAgent_name(agent_name);
		TeacherInfo teacher = teacherInfoDao.find(Long.parseLong(info.getTeacher_id()));
		String teacherName = teacher.getTeacher_name();
		info.setTeacher_name(teacherName);
		info.setCreate_time(new Date());
		info.setState("1");
		agentOrderDao.persist(info);
		logger.info("新增提单成功{}", info);
		
		AgentUser agent = agentUserDao.find(Long.parseLong(user.getCompanyid()));
		agent.setTotalUsedMoney(agent.getTotalUsedMoney() + 12000f);
		agent.setLeftMoney(agent.getLeftMoney() - 12000f);
		agentUserDao.merge(agent);
		
		ChargeDetail charge = new ChargeDetail();
		charge.setAgent_id(agent.getId());
		charge.setAgent_name(agent.getAgentName());
		charge.setCharge_money(12000f);
        charge.setLeft_money(agent.getLeftMoney());
        charge.setCharge_type(2);
        charge.setCreat_time(new Date());
        charge.setOperator_id(user.getId());
        charge.setOperator_name(user.getName());
        charge.setRemark("提单自动扣款");
        charge.setState(2);
        chargeDetailDao.persist(charge);
	}

	/**
	 * 获取后台登录用户信息
	 */
	protected MgrUser getMgrUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			throw new ZhuziException(ErrorCode.MgrUser_Not_Exist);
		}
		MgrUserDetail userDetail = (MgrUserDetail) authentication.getPrincipal();
		logger.info("登录用户userName:{}", userDetail.getUsername());
		return userDetail.getUser();
	}

	public void addAgentUser(AgentUser info) {
		info.setCreateTime(new Date());
		agentUserDao.persist(info);
		logger.info("新增代理商信息成功{}", info);
	}

	public void updateAgentUser(AgentUser info) {
		AgentUser old = agentUserDao.find(info.getId());
		old.setAgentheaderName(info.getAgentheaderName());
		old.setAgentName(info.getAgentName());
		old.setDiscount(info.getDiscount());
		old.setLeftMoney(info.getLeftMoney());
		old.setMobile(info.getMobile());
		old.setTotalUsedMoney(info.getTotalUsedMoney());
		old.setState(info.getState());
		old.setLicence(info.getLicence());
		old.setUpdateTime(new Date());
		agentUserDao.merge(old);
		logger.info("更新代理商信息成功{}", info);
	}

	public void addTeacherInfo(TeacherInfo info) {
		// info.setCreateTime(new Date());
		teacherInfoDao.persist(info);
		logger.info("新增讲师信息成功{}", info);
	}
	
	public void addMaterial(Material info) {
		// info.setCreateTime(new Date());
		materialDao.persist(info);
		logger.info("新增物料类型成功{}", info);
	}
	
	//处理物料申请
	@Transactional
	public void updateMaterialOrder(MaterialOrder info) {
		MaterialOrder old = materialOrderDao.find(info.getId());
		old.setDeal_memo(info.getDeal_memo());
		old.setState(info.getState());
		materialOrderDao.merge(old);
		
		if(info.getState() == 1)
		{
			MgrUser user = getMgrUser();
			int price = old.getPrice();
			int quanlity = old.getBuy_num();
			float total_money = price * quanlity;
			
			AgentUser agent = agentUserDao.find(Long.parseLong(old.getAgent_id()));
			agent.setTotalUsedMoney(agent.getTotalUsedMoney() + total_money);
			agent.setLeftMoney(agent.getLeftMoney() - total_money);
			agentUserDao.merge(agent);
			
			Material material = materialDao.find(old.getMaterial_id());		
			material.setSold(material.getSold()+quanlity);
			material.setStock(material.getStock()-quanlity);
			materialDao.merge(material);
			
			ChargeDetail charge = new ChargeDetail();
			charge.setAgent_id(Long.parseLong(old.getAgent_id()));
			charge.setAgent_name(old.getAgent_name());
			charge.setCharge_money(total_money);
			charge.setOperator_id(user.getId());
			charge.setOperator_name(user.getName());
			charge.setState(2);
			charge.setRemark("购买物料扣款");
			charge.setCharge_type(2);
			chargeDetailDao.persist(charge);
			
		}
		
		logger.info("处理物料申请信息成功{}", old);
	}

	
	public void updateTeacherInfo(TeacherInfo info) {
		TeacherInfo old = teacherInfoDao.find(info.getId());
		old.setState(info.getState());
		old.setTeacher_name(info.getTeacher_name());
		teacherInfoDao.merge(old);
		logger.info("更新讲师信息成功{}", info);
	}
	
	
	public void addMaterailOrder(MaterialOrder info) {
		MgrUser user = getMgrUser();
		String actortype = user.getActortype();
		logger.info("actortype:{}", actortype);
		String agentid = "0";
		String agent_name = "0";
		if (actortype.equals(ActorType.agent.getValue())) {
			agentid = user.getCompanyid();
			agent_name = user.getCompanyname();

		}
		
		MaterialOrder mOrder = new MaterialOrder();
		mOrder.setAgent_id(agentid);
		mOrder.setAgent_name(agent_name);
		mOrder.setBuy_num(info.getBuy_num());
		mOrder.setMaterial_id(info.getId());
		mOrder.setMaterial_name(info.getMaterial_name());
		mOrder.setMemo(info.getMemo());
		mOrder.setPic_path(info.getPic_path());
		mOrder.setPrice(info.getPrice()); 
		mOrder.setBuy_memo(info.getBuy_memo());
		materialOrderDao.persist(mOrder);
 
 
		logger.info("新增申请物料成功{}", info);
	}

	public void addCustomerUser(CustomerUser info) {

		logger.info("info:{}", info);
		logger.info("id:{}", info.getAgentid());
		AgentUser user = agentUserDao.findAgentUserByID(Long.parseLong(info.getAgentid()));
		logger.info("user:{}", user);
		if (null != user)
			info.setAgent_name(user.getAgentName());
		info.setCreateTime(new Date());
		customerUserDao.persist(info);

		logger.info("新增客户信息成功{}", info);
	}

	public void updateCustomerUser(CustomerUser info) {
		CustomerUser old = customerUserDao.find(info.getId());
		old.setAgent_name(info.getAgent_name());
		old.setAgentid(info.getAgentid());
		old.setCustomer_address(info.getCustomer_address());
		old.setCustomer_header_name(info.getCustomer_header_name());
		old.setCustomer_company(info.getCustomer_company());
		old.setCustomer_mobile(info.getCustomer_mobile());

		AgentUser user = agentUserDao.findAgentUserByID(Long.parseLong(info.getAgentid()));
		if (null != user)
			old.setAgent_name(user.getAgentName());

		customerUserDao.merge(old);
		logger.info("更新客户信息成功{}", info);
	}

}
